package com.gxa.shop.servlet.address;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gxa.shop.bean.pojo.Account;
import com.gxa.shop.bean.pojo.Address;
import com.gxa.shop.commons.r.R;
import com.gxa.shop.service.address.AddressService;
import com.gxa.shop.service.address.impl.AddressServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

@WebServlet(name = "AddAddressServlet",value = "/address/add")
public class AddAddressServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader bufferedReader=req.getReader();
        // 获得数据
        String data=bufferedReader.lines().collect(Collectors.joining());
        // 将数据转换成json对象
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id= jsonObject.getInteger("userId");
        String name= jsonObject.getString("recipientName");
        String phone=jsonObject.getString("recipientPhone");
        Integer regionId= jsonObject.getInteger("expressfeeId");
        String addr= jsonObject.getString("recipientAddress");
        // 获得用户id
        String token =req.getSession().getId();
        Account account=(Account) getServletContext().getAttribute(token);
        // 将数据存储在Address对象中
        Address address=new Address();
        address.setUserId(id);
        address.setRecipientName(name);
        address.setRecipientPhone(phone);
        address.setExpressfeeId(regionId);
        address.setRecipientAddress(addr);
//        address.setUserId(account.getUserId());
        // 调用service层方法
        AddressService addressService=new AddressServiceImpl();
        // 获得返回值，row
        int row= addressService.addAddress(address);
        // r，存储响应给前端的数据
        R r;
        if (row>0){
            r=R.ok("添加成功");
        }else {
            r=R.error("添加失败");
        }
        String jsonResult=JSON.toJSONString(r);
        PrintWriter writer=resp.getWriter();
        writer.write(jsonResult);
        writer.flush();
        writer.close();

    }
}
